package naga.x.platform2.utils;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import com.alibaba.fastjson.JSONObject;

import naga.x.platform2.App;
import naga.x.platform2.app.Channel;
import naga.x.platform2.app.model.GameServer;

public class PlatformUtils {

	public static String makeSign(GameServer server, Map<String, String> map) {
		Map<String, String> tree = map instanceof TreeMap ? map : new TreeMap<String, String>();
		StringBuilder buf = new StringBuilder(128);
		for (Entry<String, String> e : tree.entrySet()) {
			buf.append(e.getKey()).append('=').append(e.getValue()).append('&');
		}
		buf.append("key=").append(server.getKey());
		return CommonUtils.md5(buf.toString());
	}
	
	public static Object newError(int code) {
		return newError(code, null);
	}
	
	public static Object newError(int code, String msg) {
		JSONObject error = new JSONObject(2);
		error.put("code", code);
		error.put("msg", msg);
		return error;
	}
	
	public static Object newResponse(Object... params) {
		JSONObject res = new JSONObject();
		res.put("code", 0);
		for (int i = 0, len = params.length; i < len; i += 2) {
			res.put(params[i].toString(), params[i + 1]);
		}
		return res;
	}
	
	/**
	 * 头像映射
	 * @param channel
	 * @param icon
	 * @return 映射到图片缓存服务器的url
	 */
	public static String mappingIcon(Channel channel, String icon) {
		if (StringUtils.isNotEmpty(icon)) {
			// 请求图片缓存服务器更新头像
			String url = App.getInstance().getResourceServerUrl() + "/icon/update?channel=" + channel.name + "&url=" + CommonUtils.encodeURL(icon, IOUtils.UTF8);
			String id = StringUtils.bytesToString(HttpUtils.request(url, HttpUtils.PUT, null, null), IOUtils.UTF8);
			if (id != null && id.endsWith(channel.name)) {
				return App.getInstance().getResourceServerUrl() + "/icon/" + id;
			}
		}
		return null;
	}
	
}
